package com.example.myaudiorecord;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.myaudiorecord.MyAdapter.AudioRecordAdapter;
import com.example.myaudiorecord.Myservice.AudioRecordService;
import com.example.myaudiorecord.Util.AudioRecordUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

;

public class AudioRecordActivity extends AppCompatActivity {
    private final Object object = new Object();
    private static final int REQUEST_MANAGE_EXTERNAL_STORAGE_CODE = 1;
    private static final int REQUEST_CODE = 2;
    private static final int PERMISSION_REQUEST_CODE = 3;
    private ImageButton btnStartRecording;
    private ImageButton btnStopRecording;
    private static final int RECORDER_SAMPLERATE = 44100;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_OUT_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;

    private static AudioRecord recorder;
    private Thread recordingThread = null;
    private static boolean isRecording = false;
    private List<String> strings;
    private Chronometer chronometer;
    private ListView lv_recording;
    private AudioRecordAdapter myadpater;
    private int bufferSize;
    private AudioRecordUtil audioRecordUtil = new AudioRecordUtil();
    private Intent audioIntent;
    private int i;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_record);
        final Handler handler = new Handler();
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // 更新数据的方法
                updateData();
                // 每1秒刷新一次
                handler.postDelayed(this, 1000);
            }

            private void updateData() {
                myadpater.notifyDataSetChanged();
            }
        };
        requestPermissions();

        bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
                RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {

        }
        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, bufferSize);
        btnStartRecording = findViewById(R.id.btnStartRecording);
        btnStopRecording = findViewById(R.id.btnStopRecording);
        //录音数组
        strings = audioRecordUtil.getListStrings();
        //计时器
        chronometer = findViewById(R.id.chronometer);
        lv_recording = findViewById(R.id.lv_recording);

        myadpater = new AudioRecordAdapter(AudioRecordActivity.this, strings);
        lv_recording.setAdapter(myadpater);
        lv_recording.setOnItemClickListener((parent, view, position, id) -> {
            i = position;
            AlertDialog.Builder builder = new AlertDialog.Builder(AudioRecordActivity.this);
            builder.setTitle("播放还是删除")
                    .setItems(new String[]{"播放", "删除"}, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // 处理选择的选项
                            switch (which) {
                                case 0:
                                    playAudioRecord();
                                    break;
                                case 1:
                                    deleteAudioRecord();
                                    break;
                            }
                        }

                        private void playAudioRecord() {
                            new Thread(() -> {
                                int minBufferSize = AudioTrack.getMinBufferSize(RECORDER_SAMPLERATE, CHANNEL_CONFIG
                                        , RECORDER_AUDIO_ENCODING);
                                String s = strings.get(position);
                                File file = new File(s);
                                try {
                                    FileInputStream fileInputStream = new FileInputStream(file);
                                    AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLERATE,
                                            CHANNEL_CONFIG, RECORDER_AUDIO_ENCODING, bufferSize, AudioTrack.MODE_STREAM);
                                    audioTrack.play();
                                    byte[] buffer = new byte[minBufferSize];
                                    int bytesRead;
                                    while ((bytesRead = fileInputStream.read(buffer)) > 0) {
                                        audioTrack.write(buffer, 0, bytesRead);
                                    }
                                    fileInputStream.close();
                                    audioTrack.stop();
                                    audioTrack.release();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }).start();

//                            AudioRecordLruCache audioRecordLruCache = new AudioRecordLruCache();
//                            byte[] pcmFromCache = audioRecordLruCache.getPcmFromCache(position);
//                            if (pcmFromCache != null) {
//                                // 获取 PCM 数据成功，创建 AudioTrack 对象
//                                int minBufferSize = AudioTrack.getMinBufferSize(RECORDER_SAMPLERATE, CHANNEL_CONFIG
//                                        , RECORDER_AUDIO_ENCODING);
//                                AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLERATE,
//                                        CHANNEL_CONFIG, RECORDER_AUDIO_ENCODING, bufferSize, AudioTrack.MODE_STREAM);
//
//                                // 开始播放 PCM 数据
//                                audioTrack.play();
//                                audioTrack.write(ByteBuffer.allocateDirect(minBufferSize), 0, pcmFromCache.length);
                        }


                        private void deleteAudioRecord() {
                            String s = strings.get(position);
                            strings.remove(position);
                            File file = new File(s);
                            file.delete();
                            handler.post(runnable);
                        }
                    });
            builder.create().show();
        });

        btnStartRecording.setOnClickListener(v -> {
            handler.removeCallbacks(runnable);
            chronometer.setBase(SystemClock.elapsedRealtime());
            chronometer.start();
            btnStartRecording.setVisibility(View.INVISIBLE);
            btnStopRecording.setVisibility(View.VISIBLE);
            audioIntent = new Intent(AudioRecordActivity.this, AudioRecordService.class);
            startService(audioIntent);
        });
        btnStopRecording.setOnClickListener(v -> {
            handler.post(runnable);
            chronometer.stop();
            chronometer.setBase(SystemClock.elapsedRealtime());
            btnStartRecording.setVisibility(View.VISIBLE);
            btnStopRecording.setVisibility(View.INVISIBLE);
            stopService(audioIntent);
        });
    }

    public AudioRecord getRecorder() {
        return recorder;
    }

    public int getBufferSize() {
        return bufferSize;
    }

    public int getI() {
        return i;
    }

    private void requestPermissions() {
//        录音权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
//             如果没有权限，则请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO},
                    PERMISSION_REQUEST_CODE);
        }
        //        本地文件权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivityForResult(intent, REQUEST_MANAGE_EXTERNAL_STORAGE_CODE);
            }
        } else {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
            }
        }


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        recorder.release();
        stopRecording();
    }

    private void stopRecording() {
        isRecording = false;
        recorder.stop();
        recorder = null;
        recordingThread = null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("wjh", "录音权限已被授予");
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
                    recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                            RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                            RECORDER_AUDIO_ENCODING, bufferSize);
                }

            } else Log.d("wjh", "录音权限已被拒绝");
        }
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("wjh", "本地文件权限已被授予");
            } else Log.d("wjh", "本地文件权限已被拒绝");
        }

    }
}